package com.hmtech.aup.presentation.home

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.hmtech.aup.R
import com.hmtech.aup.domain.vo.StyleVO

class StyleItemAdapter : ListAdapter<StyleVO, StyleItemAdapter.StyleViewHolder>(StyleDiff()) {
    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): StyleViewHolder {
        val v = LayoutInflater.from(parent.context)
            .inflate(R.layout.view_style_item, parent, false)
        return StyleViewHolder(v)
    }

    override fun onBindViewHolder(holder: StyleViewHolder, position: Int) {
        holder.bind(getItem(position))
    }

    class StyleViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        private val coverImgIv: ImageView = itemView.findViewById(R.id.ivCoverImg)
        private val titleTv: TextView = itemView.findViewById(R.id.tvTitle)

        fun bind(style: StyleVO) {
            Glide.with(itemView.context)
                .load(style.coverImgUrl)
                .placeholder(R.drawable.loading_placeholder)
                .error(R.drawable.loading_placeholder)
                .fitCenter()
                .into(coverImgIv)
            titleTv.text = style.title
        }
    }

    private class StyleDiff : DiffUtil.ItemCallback<StyleVO>() {
        override fun areItemsTheSame(old: StyleVO, new: StyleVO) = old.id == new.id
        override fun areContentsTheSame(old: StyleVO, new: StyleVO) = old == new
    }
}
